$(document).ready(function(){
/***********************************************************Table**********************************************************************/
/******************************************************Home Page (Request)*************************************************************/
/* Set Auto Default to view the list of file from the database */
function defaultTableView(){
    page = 1;
    // Request to Approve
    $.post("/ajaxTable/tblRequestToApprove", {action:"RequestApprove",page:page}, function(table){
            $("#requestToApprove_tbl").html(table);
    });
    // Pending Request
    $.post("/ajaxTable/tblPendingAction", {action:"PendingRequest",page:page}, function(table){
            $("#pending_action_tbl").html(table);
    });
    // My Request
    $.post("/ajaxTable/tblMyRequest", {action:"MyRequest",page:page}, function(table){
            $("#myRequest_tbl").html(table);
    });
    // History of Approved Request
    $.post("/ajaxTable/tblHistoryRequest", {action:"HistoryApproved",page:page}, function(table){
            $("#historyApprovedRequest_tbl").html(table);
    });
    // Drop Table Request
    $.post("/ajaxTable/tbldrop", {action:"drop",page:page}, function(table){
            $("#dropTable_tbl").html(table);
    });
    // Revision List (ORGANIZATIONAL CHART)
    $.post("/ajaxTable/tblRevisionList", {action:"RevisionList",page:page}, function(table){
            $("#revisiontList_tbl").html(table);
    });
    // Registration Request List (User Management)
    $.post("/ajaxTable/tblRegistrationRequest", {action:"RegistrationRequest",page:page}, function(table){
            $("#registrationRequest_tbl").html(table);
    });
    // User List (User Management)
    $.post("/ajaxTable/tblUserList", {action:"UserList",page:page}, function(table){
            $("#userList_tbl").html(table);
    });
    // Floating Accounts (User Management)
    $.post("/ajaxTable/tblFloatingAccounts", {action:"FloatingAcc",page:page}, function(table){
            $("#floatingAcct_tbl").html(table);
    });
    // Deleted Account (User Management)
    $.post("/ajaxTable/tblDeletedAccounts", {action:"DeletedAcc",page:page}, function(table){
            $("#DeletedAcc_tbl").html(table);
    });
    // Approver Button (Administer)
    $.post("/ajaxTable/tblApproverButton", {action:"ActionStatus",page:page}, function(table){
            $("#tblActionButtonList").html(table);
    });
    // Approver Status (Administer)
    $.post("/ajaxTable/tblApproverStatus", {action:"ActionStatus",page:page}, function(table){
            $("#tblActionStatusList").html(table);
    });
    // Add Position
    $.post("/ajaxTable/tblPosition", {action:"Default",page:page}, function(table){
            $("#tblAddPosition").html(table);
    });
}
// Default View for the table in home page of formalistic (List of Request)
defaultTableView();


/*-------------------------------------------------------------------------------------------------------------------*/
// Login Portal To Formalistic
loginAuth = {
    login : function(){
        $("#login").live("click", function(){
            action = "login"
            username = $(".username").val();
            password = $(".password").val();
            $.post("/ajax/login",{username:username,password:password,action:action}, function(e){
                if(e=="Yes"){
                    window.location.replace("/formalistic");
                }else{
                    showNotification({
                        message: "Invalid Username & Password, Please try again.",
                        type: "error",
                        autoClose: true,
                        duration: 3
                    });
                    //$(".username").css("border","1px solid #fc93a5");
                    //$(".password").css("border","1px solid #fc93a5");
                }
            });
        });
    },
    getImage : function(){
        $(".username").live("keyup", function(){
            value = $(this).val();
            action = "getimage";
            $.post("/ajax/login",{value:value,action:action}, function(data){
                if(data!="No Record Found."){
                    $("#userImageLoad").attr("src",data).css({height:"48px",width: "48px"});
                }else{
                    $("#userImageLoad").attr("src","/images/avatar/avatar.png");
                    
                }
            });
        });
    }
}
    
    
// For Searching, Pagination, Sortable
table = {
    /*-------------------------------------------------------------------------------------------------------------------*/
    // Advance Searching
    searchByDateRequestToApprove : function(elements){
        $(elements).live("click", function(){
            if($(this).attr("checked",true)){
                search_action = $(this).attr("data-search-action");
                page = 1;
                $(".recordSearch").val(null);
                $("#search_alls").val(null);
                $("#search_from").val(null);
                $("#search_to").val(null);
                $("#search_date").show();
                $("#search_by").hide();
                $("#search_all").hide();
                
                $(".searchAll").attr("checked",false); 
                $(".defaultDa").attr("checked",false);
                
                // activeSearch
                $(".activeSearch").attr("data-search-action","searchDate");
                // Request to Approve
                //$.post("/ajaxTable/tblRequestToApprove", {action:"RequestApprove",page:page}, function(table){
                //        $("#requestToApprove_tbl").html(table);
                //});
                
            }
        });  
    },
    searchAllRequestToApprove : function(element){
        $(element).live("click", function(){
            if($(this).attr("checked",true)){
                search_action = $(this).attr("data-search-action");
                page = 1;
                $(".recordSearch").val(null);
                $("#search_alls").val(null);
                $("#search_from").val(null);
                $("#search_to").val(null);
                $("#search_date").hide();
                $("#search_by").hide();
                $("#search_all").show();
                
                $(".searchByDate").attr("checked",false); 
                $(".defaultDa").attr("checked",false);
                // Request to Approve
                $.post("/ajaxTable/tblRequestToApprove", {action:"RequestApprove",page:page}, function(table){
                        $("#requestToApprove_tbl").html(table);
                });
            }    
        });
    },
    defaultDaRequestToApprove : function(elements){
        $(elements).live("click", function(){
            if($(this).attr("checked",true)){
                search_action = $(this).attr("data-search-action");
                data_location = $(this).attr("data-location");
                data_table = $(this).attr("data-table");
                page = 1;
                $(".recordSearch").val(null);
                $("#search_alls").val(null);
                $("#search_from").val(null);
                $("#search_to").val(null);
                $("#search_date").hide();
                $("#search_by").show();
                $("#search_all").hide();
                
                $(".searchAll").attr("checked",false); 
                $(".searchByDate").attr("checked",false);
                
                // Request to Approve
                $.post("/ajaxTable/"+data_location, {action:"RequestApprove",page:page}, function(table){
                        $("#"+data_table).html(table);
                });
            }      
        });
    },
    
    
    //for Searching Default
    /*search_requestApprove : function(elements){
        $(elements).live("keyup",function(){
            data_location_defaulit = $(this).attr("data-location-default");
            data_location = $(this).attr("data-location");
            data_table = $(this).attr("data-table");
            search_action = $(this).attr("data-search-action");
            value = $(this).val();
            page = 1;
            if(value!=""){
                // Request to Approve
                $.post("/ajaxTable/"+data_location, {action:"search_requestApprove",page:page,value:value}, function(table){
                        $("#"+data_table).html(table);
                });
            }else{
                // Request to Approve
                $.post("/ajaxTable/"+data_location, {action:data_location_defaulit,page:page}, function(table){
                        $("#"+data_table).html(table);
                });
            }
                
        });
    },*/
    // For Searching ALL
    search_requestApprove_alls : function(elements){
        $(elements).live("keyup", function(){
            searchInput = $(this).val();
            data_location = $(".activeSearch").attr("data-location");
            data_table = $(".activeSearch").attr("data-table");
            $("tr."+data_table).each(function(){
                var re = new RegExp(searchInput, 'gi');
                if($(this).text().match(re) === null )
                {
                    $(this).hide();
                    $(".pagination").hide();
                }else{
                    $(this).show();
                    $(".pagination").show();
                }
            });
        });
    },
    // For Date Search
    searchDate : function(elements){
        $(elements).live("click", function(){
            data_location = $(".activeSearch").attr("data-location");
            data_table = $(".activeSearch").attr("data-table");
            search_action = $(".activeSearch").attr("data-search-action");
            dateF = $("#search_from").val();
            dateT = $("#search_to").val();
            value = dateF + "," + dateT;
            page = 1;
            if(dateF==""||dateT==""){
                showNotification({
                    message: "Dont Leave a blank field.",
                    type: "error",
                    autoClose: true,
                    duration: 3
                });
            }else{
                $.post("/ajaxTable/"+data_location, {action:search_action,page:page,value:value}, function(table){
                    $("#"+data_table).html(table);
                });
            }
            
        });
    },
    /*-------------------------------------------------------------------------------------------------------------------*/
    //for New Searching
    recordSearch : function(elements){
        $(elements).live("keyup", function(){
            if($(".plusBox").hasClass("activeSearch")=== true){
                data_location_defaulit = $(".activeSearch").attr("data-location-default");
                data_location = $(".activeSearch").attr("data-location");
                data_table = $(".activeSearch").attr("data-table");
                search_action = $(".activeSearch").attr("data-search-action");
                value = $(this).val();
                page = 1;
                if(value!=""){
                    $.post("/ajaxTable/"+data_location, {action:search_action,page:page,value:value}, function(table){
                            $("#"+data_table).html(table);
                    });
                }else{
                    $.post("/ajaxTable/"+data_location, {action:data_location_defaulit,page:page}, function(table){
                            $("#"+data_table).html(table);
                    });
                }
            }
        });
    },
    /*-------------------------------------------------------------------------------------------------------------------*/
    //for Sorting
    sortRequestApprove : function(element){
        counterSort = 0;
        $("tr"+element+" >th").live("click", function(){
            if($(this).attr("rel")!="notAllowed"){
                // Get value of the selected header in the table
                //dataSortValue = $(this).closest('table').find('th').eq($(event.target).index()).attr("id");
                page = $(".requestToApprove_page").attr("p");
                dataSortValue = $(this).attr("data-search");
                action = $(this).attr("data-tag-action");
                elementsShow = $(this).attr("data-element");
                data_location = $(this).attr("data-location");
                
                // Request to Approve
                    tblRequestToApprove(action,page,elementsShow,dataSortValue,counterSort,data_location);
                counterSort++;
            }
        });
    },
    /*-------------------------------------------------------------------------------------------------------------------*/
    //for pagination
    tablePagination : function(elements){
        $(elements).live('click',function(){
            var page = $(this).attr('p');
            action = $(this).attr('data-tag-action');
            value = $(this).attr("data-value");
            
                // Request to Approve
                $("#requestToApprove").attr("p",page);
                $.post("/ajaxTable/tblRequestToApprove", {action:action,page:page,value:value}, function(table){
                        $("#requestToApprove_tbl").html(table);
                });
                
                // Pending Request    
                $.post("/ajaxTable/tblPendingAction", {action:action,page:page,value:value}, function(table){
                        $("#pending_action_tbl").html(table);
                });
                
                // My Request    
                $.post("/ajaxTable/tblMyRequest", {action:action,page:page,value:value}, function(table){
                        $("#myRequest_tbl").html(table);
                });
                
                // History Request   
                $.post("/ajaxTable/tblHistoryRequest", {action:action,page:page,value:value}, function(table){
                        $("#historyApprovedRequest_tbl").html(table);
                });
                
                // Draft   
                $.post("/ajaxTable/tbldrop", {action:action,page:page,value:value}, function(table){
                        $("#dropTable_tbl").html(table);
                });
                        
                // History Request   
                $.post("/ajaxTable/tblRevisionList", {action:action,page:page,value:value}, function(table){
                        $("#revisiontList_tbl").html(table);
                });
                
                // History Request   
                $.post("/ajaxTable/tblUserList", {action:action,page:page,value:value}, function(table){
                        $("#userList_tbl").html(table);
                });
                // Action Button
                $.post("/ajaxTable/tblApproverButton", {action:action,page:page,value:value}, function(table){
                        $("#tblActionButtonList").html(table);
                });
                
                // Action Status
                $.post("/ajaxTable/tblApproverStatus", {action:action,page:page,value:value}, function(table){
                        $("#tblActionStatusList").html(table);
                });
                // Add Position
                $.post("/ajaxTable/tblPosition", {action:action,page:page,value:value}, function(table){
                        $("#tblAddPosition").html(table);
                });
        });
        
    }
}
/***********************************************************Formalistic**********************************************************************/
/************************************************************Create Form*********************************************************************/
/* View Form when Workflow is activated in the tab */
craeteForm = {
    setviewCreatedForm : function(elements){
        $(elements).live("click", function(){
            $(".main_container").hide(); // Hide Workflow
            $(this).hide();
            $(".forForm").show(); // Show Form
            $(".fieldsettings").addClass("active"); // Update Active Tab
                $("#tab2").show();
            $(".workflowSettings").removeClass("active"); // Remove Active Tab
                $(".wofkflowTab").hide();
                $(".menuMaintContainer").hide(); // Hide menu of the workflow
            
        });
    },
    /* TAB */
    tab : function(elements){
        $("ul.tabs li").live("click",function() {
                $("ul.tabs li").removeClass("active");
                $(this).addClass("active");
                $(".tab_content").removeClass('display').hide();
                var activeTab = $(this).attr("rel");
                $("#"+activeTab).addClass('display').show();
                $(".setObjectForm").css("background-color","#fff");
                if($(this).hasClass("workflowSettings")){
                    $(".setviewCreatedForm").show();
                }else{
                    $(".setviewCreatedForm").hide();
                    $(".main_container").hide(); // Hide Workflow
                    $(".forForm").show(); // Show Form
                    $(".workflowSettings").removeClass("active"); // Remove Active Tab
                        $(".wofkflowTab").hide();
                        $(".menuMaintContainer").hide(); // Hide menu of the workflow
                }
        });
    }
}
/************************************************************Show Form in Modal*********************************************************************/
// Get Modal Box Content per Action
modal = {
    showModal : function(elements){
        $(elements).live("click", function(){
            action = $(this).attr("data-action");
            dataID = $(this).attr("data-id");
            $.post("/ajax/modalBox", {action:action,dataID:dataID}, function(value){
                $("#modalBox").html(value);
                $("#modalBox").addClass("login");
            });
        });
    }
    
}
/***************************************************************************************************************************************/
/******************************************************REGISTRATION********************************************************************/
users = {
    registration : function(){
        //User
        $(".reg_user").live("click",function(){
            $(".sign_up").ajaxForm(function(data){
                if(data=="true"){
                    showNotification({
                       message: "Congratulation your information was sent to your company admin, please wait for their approval before you log in.",
                       type: "success",
                       autoClose: true,
                       duration: 5
                    });
                    $("html").append('<meta http-equiv="refresh" content="3">'); //for refresh
                }else{
                    showNotification({
                        message: data,
                        type: "error",
                        autoClose: true,
                        duration: 5
                     });
                }
            }).submit();
        });
    },
    registrationCompany : function(){
        // Register Company
        $(".reg_company").live("click",function(){
            $(".sign_up_company").ajaxForm(function(data){
                if(data=="true"){
                    showNotification({
                       message: "Congratulation your company name is now Registered. You'r now be able to login into our portal.",
                       type: "success",
                       autoClose: true,
                       duration: 5
                    });
                    $("html").append('<meta http-equiv="refresh" content="3">'); //for refresh
                }else{
                    showNotification({
                        message: data,
                        type: "error",
                        autoClose: true,
                        duration: 5
                     });
                }
            }).submit();
        });
    }
}
});
/*********************************************************************CSS************************************************************************/
// CSS 
myFunctions = {
    menuHoveringIn : function(){
        $(".userMenu").live("mouseover",function(){
            $(".userSeparator").css("border-color","#606060");
        });
    },
    menuHoveringOut : function(){
        $(".userMenu").live("mouseleave",function(){
            $(".userSeparator").css("border-left","1px solid #6f6f6f");
        });
    },
    // Showing of Advance Search
    advanceSearching : function(){
        $(".advanceSearching").live("click", function(){
            $("#advanceSearch").show();
            $(this).hide();
        });
    },
    collapseTab : function(){
        $(".plusBox").live("click",function(){
            getRel = $(this).attr("data-dropping");
            data_location_defaulit = $(".activeSearch").attr("data-location-default");
            data_location = $(".activeSearch").attr("data-location");
            data_table = $(".activeSearch").attr("data-table");
            search_action = $(".activeSearch").attr("data-search-action");
            
            $(".plusBox").each(function(){
                if(getRel==$(this).attr("data-dropping")){
                    $("."+getRel).slideDown();
                    $("#"+this.id).addClass("activeSearch");
                    // Advance Searching (Remove Value and hide other fields)
                    $(".defaultDa").attr("checked",true);
                    $(".recordSearch").val(null);
                    $("#search_alls").val(null);
                    $("#search_from").val(null);
                    $("#search_to").val(null);
                    $("#search_date").hide();
                    $("#search_by").show();
                    $("#search_all").hide();
                    $("#"+this.id).attr("src","/images/icon/minus.png");
                    
                    $.post("/ajaxTable/"+data_location, {action:data_location_defaulit,page:page}, function(table){
                            $("#"+data_table).html(table);
                    });
                }else{
                    $("#"+this.id).removeClass("activeSearch");
                    $("#"+this.id).attr("src","/images/icon/plus.png");
                    $("."+$(this).attr("data-dropping")).slideUp();
                    $(".activeSearch").attr("data-search-action","search_request");
                }
            })
            if($(this).attr("accordion-type")!=undefined){
                $(this).addClass("minusBox");
                $(this).removeClass("plusBox");
            }
        });
        $(".minusBox").live("click",function(){
            $("."+$(this).attr("data-dropping")).slideUp();
            $(this).addClass("plusBox");
            $(this).removeClass("minusBox");
            $("#"+this.id).attr("src","/images/icon/plus.png");
        })
    }
}
/***************************************************************************************************************************************/
/******************************************************Edit Information*****************************************************************/
user_info = {
    editBasicInfo : function(){
        $(".editBasicInfo").live("click", function(){
            action = "saveEditedUser";
            $.post("/ajax/editUser", $(".basicInformation").serialize()+"&action=" + action, function(e){
               if(e=="Please input your basic information to the fields."){
                    showNotification({
                        message: e,
                        type: "error",
                        autoClose: true,
                        duration: 2
                     });
                
               }else{
                    if(e=="Wrong Email Format."){
                        showNotification({
                            message: e,
                            type: "error",
                            autoClose: true,
                            duration: 2
                         });
                    }else{
                        showNotification({
                            message: e,
                            type: "success",
                            autoClose: true,
                            duration: 3
                         });
                        $(".showCancelEdit").hide();
                        $(".showEditInfo").show();
                        $(".editBasicInfo").hide();
                        $(".basicInfo").hide();
                        $(".hidebasicInfo").show();
                        
                    }
               }
            });
            
        });
    },
    // Edit Icon (show edit fields)
    showEditInfo : function(){
        $(".showEditInfo").live("click", function(){
            $(this).hide();
            $(".showCancelEdit").show();
            $(".editBasicInfo").show();
            $(".basicInfo").show();
            $(".hidebasicInfo").hide();
        });
    },
    // Cancel Editing
    showCancelEdit : function(){
        $(".showCancelEdit").live("click", function(){
            $(this).hide();
            $(".showEditInfo").show();
            $(".editBasicInfo").hide();
            $(".basicInfo").hide();
            $(".hidebasicInfo").show();
        });
    },
    // Update Username  of the user
    updateUsername : function(){
        $(".updateUsername").live("click", function(){
            newUsername = $(".newUsername").val();
            oldUsername = $(".oldUsername").val();
            action = "editUsername";
            $.post("/ajax/editUser", {action:action,newUsername:newUsername,oldUsername:oldUsername}, function(e){
                if(e=="Input your new Username."){
                    showNotification({
                        message: e,
                        type: "error",
                        autoClose: true,
                        duration: 2
                     });
                }else{
                    if(e=="Successfully Updated."){
                        showNotification({
                            message: e,
                            type: "success",
                            autoClose: true,
                            duration: 3
                         });
                        $(".oldUsername").val(newUsername);
                    }
                }
            });
        });
    },
    // Update Password of the user
    updatePassword : function(){
        $(".updatePassword").live("click", function(){
            oldPassword = $("#oldPassword").val();
            newPassword = $("#newPassword").val();
            retypePassword = $("#retypePassword").val();
            action = "newPassword";
            if(oldPassword=="" || newPassword==""|| retypePassword==""){
                showNotification({
                    message: "Please fill those required fields.",
                    type: "error",
                    autoClose: true,
                    duration: 2
                });
            }else{
                if(newPassword!=retypePassword){
                    showNotification({
                        message: "Your new password and retype password is not the same.",
                        type: "error",
                        autoClose: true,
                        duration: 2
                    });
                }else{
                    $.post("/ajax/editUser/",{action:action,newPassword:newPassword,oldPassword:oldPassword}, function(e){
                        if(e=="no"){
                            showNotification({
                                message: "Your Old password does'nt match in our records.",
                                type: "error",
                                autoClose: true,
                                duration: 2
                            });
                        }else{
                            showNotification({
                                message: "Your password was successfully changed.",
                                type: "success",
                                autoClose: true,
                                duration: 2
                            });
                            $("#oldPassword").val(null);
                            $("#newPassword").val(null);
                            $("#retypePassword").val(null);
                             
                        }
                        
                    });
                }
            }    
        });
    }
}
//---------------------------------------------------------------------------------------------//
//---------------------------------------------------------------------------------------------//
//---------------------------------------------------------------------------------------------//
// Plugin for this Administer Module
administerModule = {
    // Announcement
    viewMore : function(element){
        $(element).live("click", function(){
            announcementLength = $(this).attr("data-announcement-length");
            announcement = $(this).attr("data-announcement");
            dataID = $(this).attr("data-id");
            viewAllAnnouncement = announcement.substr(0, announcementLength);
            action = $(this).attr("data-action");
            $("#"+action+dataID).html(viewAllAnnouncement + "\n" + "<br /><br /><a class='hrefPostAction' id='lessMore' data-id='"+dataID+"' data-action='"+action+"' data-announcement-length='"+announcementLength+"' data-announcement='"+announcement+"'>Less More</a>");
        });
    },
    lessMore : function(element){
        $(element).live("click", function(){
            announcementLength = $(this).attr("data-announcement-length");
            announcement = $(this).attr("data-announcement");
            viewAllAnnouncement = announcement.substr(0, 200);
            dataID = $(this).attr("data-id");
            action = $(this).attr("data-action");
            $("#"+action+dataID).html(viewAllAnnouncement + "...\n" + "<br /><br /><a class='hrefPostAction' id='loadMore' data-id='"+dataID+"' data-action='"+action+"' data-announcement-length='"+announcementLength+"' data-announcement='"+announcement+"'>View More</a>");
        });
    },
    /*
    saveNewAnnouncement : function(element){
        $(element).live("click",function(){
            announcement = $(".announcement").val();
            $.post("/ajax/actionAdmin",{action:"updateAnnouncement",announcement:announcement},function(data){
                showNotification({
                    message: "Announcement Updated",
                        type: "success",
                   autoClose: true,
                   duration: 3
                });
                $("html").append('<meta http-equiv="refresh" content="2">'); //for refresh
            })
        })
    },*/
    // View Settings
    
    appendNumCols : function(element){
        a = 0;
        $(element).live("click", function(){
            numCols = $("#numCols").val(); // input number of columns you want
            // Show created cols according to the inputed number of columns
            if(numCols==0){
                showNotification({
                    message: "Please input the number of column that you want to create.",
                    type: "error",
                    autoClose: true,
                    duration: 3
                });
            }else{
                if(a==0){
                    for (var n = 1; n <= numCols; ++ n){
                        $(".showCreatedCols").append(
                        '<div class="fields"><div class="label fontGray" id="labelObject">Column '+n+'*:</div><div class="input_position"><input type="text" name="setofCols[]" id="setofCols" class="input-medium" /></div></div>');
                    }
                    $('<div class="fields" style="border-bottom:none;margin-top:5px;"><div class="label fontGray" id="labelObject"></div><div class="input_position"><input type="button" class="button-medium" value="Go" id="saveSetofCols"/></div></div>').insertAfter(".showCreatedCols");
                }else{
                    showNotification({
                        message: "You cannot",
                        type: "error",
                        autoClose: true,
                        duration: 3
                    });
                }
                a++;
            }
        });
    },
    // Save the setted columns to the database
    saveSetofCols : function(element){
        $(element).live("click", function(){
            numCols = $("#numCols").val(); // input number of columns you want
            setCols = $(":text[name='setofCols[]']").map(function(){
                return $(this).val();
            }).get().join(',');
            // Determine if all inputs created in columns has all values
            emptyInputs = $(this).parent().find('input[id="setofCols"]').filter(function() { return $(this).val() == ""; });
            if (emptyInputs.length){
                showNotification({
                    message: "Please dont leave it blank.",
                    type: "error",
                    autoClose: true,
                    duration: 3
                });
            }else{
                //alert(setCols)
                // Get tbform
                action = "getFormField";
                $.post("/ajax/administerMod", {action:action,numCols:numCols,setCols:setCols}, function(getFormField){
                    $(".showFormField").html(getFormField);
                });
            }
        });
    },
    enabledCol : function(elements){
        $(elements).live("click", function(){
            dataCounter = $(this).attr("data-enem-col");
            $("select#selectLabel").attr("data-enem-col",dataCounter);
        })
    },
    //
    selectLabel : function(elements){
        $(elements).live("change", function(){
            //$("#selectLabel > option:selected").each(function(){
            //    $(this).remove().appendTo("#list2");
            //});
            enemCol = $("select#selectLabel").attr("data-enem-col");
            fieldID = $("#selectLabel option:selected").attr("data-field-id");
            if(enemCol==""){
                showNotification({
                    message: "Please select one option of the field where do you want to add this.",
                    type: "error",
                    autoClose: true,
                    duration: 3
                });
            }else{
                if($("#insertSelectedCol_"+enemCol).val()!=""){
                    showNotification({
                        message: "Cannot update using this,",
                        type: "error",
                        autoClose: true,
                        duration: 3
                    });
                }else{
                    selectedfieldCol = $("#selectLabel option:selected").text();
                    $("#selectLabel option:selected").remove();
                    $("#insertSelectedCol_"+enemCol).val(selectedfieldCol);
                    $("#insertSelectedCol_"+enemCol).attr("data-field-id",fieldID);
                    
                }
            }
            
        });
    },
    removeSelectedField : function(elements){
        $(elements).live("click", function(){
            enemCol = $(this).attr("data-enem-col");
            selectedfieldCol = $("#insertSelectedCol_"+enemCol).val();
            fieldID = $("#insertSelectedCol_"+enemCol).attr("data-field-id");
            if(selectedfieldCol==""){
                showNotification({
                    message: "Field is blank.",
                    type: "error",
                    autoClose: true,
                    duration: 3
                });
            }else{
                $("#selectLabel").append("<option data-field-id="+fieldID+">"+selectedfieldCol+"</option>");
                $("#insertSelectedCol_"+enemCol).val(null);
                $("#enabledCol_"+enemCol).removeAttr("checked");
                $("#insertSelectedCol_"+enemCol).removeAttr("data-field-id");
                $("select#selectLabel").attr("data-enem-col","");
            }
            
        });
    },
    saveModSettings : function(elements){
        
        $(elements).live("click", function(){
            a = 1;
            b = 1;
            companyID = $(".insertSelectedCol").attr("data-company-id");
            // Determine if all inputs created in columns has all values
            emptyInputs = $(this).parent().find('.insertSelectedCol').filter(function() { return $(this).val() == ""; });
            if (emptyInputs.length){
                showNotification({
                    message: "Please dont leave it blank.",
                    type: "error",
                    autoClose: true,
                    duration: 3
                });
            }else{
                action = "saveFormField";
                numCols = $("#numCols").val(); // number of columns
                // column set - can set the title of the created columns
                
                setofCols = $(":text[name='setofCols[]']").map(function(){
                    return   a++ + "->" +$(this).val();
                    
                }).get().join(",");
                
                //
                dataFieldSet = $(":text[name='dataFieldSet[]']").map(function(){
                    return b++ + "->" +$(this).attr("data-field-id");
                }).get().join(",");
                
                //alert(setofCols + "\n" + dataFieldSet)
                
                // Save to the database
                $.post("/ajax/administerMod", {action:action,setofCols:setofCols,dataFieldSet:dataFieldSet,companyID:companyID,numCols:numCols}, function(data){
                    
                        if(data=="Saved"){
                            showNotification({
                                message: "Created Column was successfully saved.",
                                type: "success",
                                autoClose: true,
                                duration: 3
                            });
                        }
                });
            }
            
        });
    }
}

checkbox = {
    singleSelect : function(element){
        /* Single Check of the checkbox for deleting the record from the database in data table */
        $(element).live("click",function(){
            if(this.checked){
                // Select Single Checkbox
                var list = $(':checkbox[name="singleSelectAll[]"]:checked').map(function(){
                return $(this).attr("data-id"); // Get an ID of the document
                }).get().join(',');
                $(".viewNewMB").attr("data-id",list); // Where the ID input in the textbox
            }else{
                // Remove Unchecked ID in the textbox
                var list = $(':checkbox[name="singleSelectAll[]"]:checked').map(function(){
                return $(this).attr("data-id");
                }).get().join(',');
                $(".viewNewMB").attr("data-id",list);
            }
        });
    },
    selectAll : function(){
        /* Select All the checkbox in sinlge checked of the header Checkbox */
        $(".selectAll").live("click",function(){
            if(this.checked){
                $(".singleSelectAll").each(function(){
                    $(this).attr("checked",true);
                    var list = $(':checkbox[name="singleSelectAll[]"]:checked').map(function(){
                    return $(this).attr("data-id");
                    }).get().join(',');
                    $(".viewNewMB").attr("data-id",list);
                });
            }else{
                $(".singleSelectAll").each(function(){
                    $(this).attr("checked",false);
                    var list = $(':checkbox[name="singleSelectAll[]"]:checked').map(function(){
                    return $(this).attr("data-id");
                    }).get().join(',');
                    $(".viewNewMB").attr("data-id",list);
                });
            }
        });
    }
}
// Sending Message to the selected user
message = {
    loadMessage : function(){
        loadMessage();
    },
    sendMessage : function(){
        $(".sendMessage").live("click",function(){
            $(".leftMessagePanel").fadeOut();
            action = "sendMessage";
            dataID = $(this).attr("data-id");
            Msubject = $(".Msubject").val();
            Mmessage = $(".Mmessage").val();
            if(dataID==""){
                showNotification({
                    message: "Please choose an user to proceed.",
                    type: "error",
                    autoClose: true,
                    duration: 3
                });
            }else{
                if(Msubject==""||Mmessage==""){
                    showNotification({
                        message: "Dont leave those fields blank.",
                        type: "error",
                        autoClose: true,
                        duration: 3
                    });
                }else{
                    $.post("/ajax/getMessage", {action:action,dataID:dataID,Msubject:Msubject,Mmessage:Mmessage}, function(e){
                        //if(e=="Message was successfully send."){
                            showNotification({
                                message: e,
                                type: "success",
                                autoClose: true,
                                duration: 3
                            });
                            $(".Msubject").val(null);
                            $(".Mmessage").val(null);
                            loadMessage();
                        //}
                           
                    });
                }
            }
        });
        
    },
    replyMessage : function(){
        $('html').keydown(function(e){
            if($(".replyMessage").hasClass("reply")==true){
                if(e.keyCode == 13){
                    dataID = $(".replyMessage").attr("data-id");
                    replyVal = $(".replyMessage").val();
                    if(replyVal==""){
                        showNotification({
                            message: "Please type your message to proceed.",
                            type: "error",
                            autoClose: true,
                            duration: 3
                        });
                        
                    }else{
                        $.post("/ajax/getMessage",{action:"replyMessage",dataID:dataID,replyVal:replyVal},function(e){
                            //if(e==""){
                                $(".userNewMessage:last").append(e);
                                $(".replyMessage").val(null);
                                $('.userNewMessage').scrollTop(99999999*10);  
                            //}
                            
                        });
                    }
                    $(".replyMessage").val(null);
                }
            }
        });
    },
    deleteMessage : function(){
        // Delete Message Send by the sender
	$(".deleteConversation").live("click", function(){
	    $(".viewMessageDeleteBox").show();
            $(".selectAllDeleteMessage").show();
            $(".deleteMessageFromDB").show();
            $(this).hide();
            $(".cancenDeleteConversation").show();
	});
    },
    selectToDeleteMessage : function(){
        // Delete now the message
	$(".singleDeleteSelectedMessage").live("click", function(){
	    if(this.checked){
                // Select Single Checkbox
                var list = $(':checkbox[name="singleDeleteSelectedMessage[]"]:checked').map(function(){
                return $(this).attr("data-id"); // Get an ID of the document
                }).get().join(',');
                $(".deleteMessageFromDB").attr("data-id",list); // Where the ID input in the textbox
                
                    // Select Single Checkbox
                    var list1 = $(':checkbox[name="singleDeleteSelectedMessage[]"]:checked').map(function(){
                    return $(this).attr("data-message-id"); // Get an ID of the document
                    }).get().join(',');
                    $(".deleteMessageFromDB").attr("data-message-id",list1); // Where the ID input in the textbox
            }else{
                // Remove Unchecked ID in the textbox
                var list = $(':checkbox[name="singleDeleteSelectedMessage[]"]:checked').map(function(){
                return $(this).attr("data-id");
                }).get().join(',');
                $(".deleteMessageFromDB").attr("data-id",list);
                    // Remove Unchecked ID in the textbox
                    var list1 = $(':checkbox[name="singleDeleteSelectedMessage[]"]:checked').map(function(){
                    return $(this).attr("data-message-id");
                    }).get().join(',');
                    $(".deleteMessageFromDB").attr("data-message-id",list1);
            }
	});
    },
    deleteMessageFromDB : function(){
        $(".deleteMessageFromDB").live("click",function(){
            
            dataID = $(this).attr("data-id");
            action = "deleteMyMessage";
            messageID = $(this).attr("data-message-id");
            if(dataID==""||messageID==""){
                showNotification({
                    message: "Please select a message to proceed.",
                    type: "error",
                    autoClose: true,
                    duration: 3
                });
                
            }else{
                $(".leftMessagePanel").fadeOut();
                // Delete message from the database
                $.post("/ajax/getMessage",{action:action,dataID:dataID,messageID:messageID},function(e){
                    //if(e=="Message was successfully deleted."){
                        showNotification({
                            message: "Message was successfully deleted.",
                            type: "success",
                            autoClose: true,
                            duration: 3
                        });
                        loadMessage();
                        $(".singleDeleteSelectedMessage").attr("checked",false);
                        $(".viewMessageDeleteBox").hide();
                        $(".selectAllDeleteMessage").hide();
                        $(".deleteMessageFromDB").hide();
                        $(".cancenDeleteConversation").hide();
                        $(".deleteConversation").show();
                        $(".deleteMessageFromDB").attr("data-id","");
                        $(".deleteMessageFromDB").attr("data-message-id","");
                        $('.panel').animate({left: "0px"});
                    //}
                });
            }
            
        });
    },
    cancelDeleteMessage : function(){
        $(".cancenDeleteConversation").live("click",function(){
            $(".singleDeleteSelectedMessage").attr("checked",false);
            $(".viewMessageDeleteBox").hide();
            $(".selectAllDeleteMessage").hide();
            $(".deleteMessageFromDB").hide();
            $(this).hide();
            $(".deleteConversation").show();
            $(".deleteMessageFromDB").attr("data-id","");
            $(".deleteMessageFromDB").attr("data-message-id","");
        });
    },
    inboxMessage : function(){
        $(".inboxMessage").live("click",function(){
            loadMessage();
        });
    },
    refresher : function(){
        setInterval(function(){
            //$.post("/ajax/getMessage",{action:"refreshReply"},function(e){
            //    $("#loadMessageReply").html(e);
            //});
            
        },5000);
    }
}

helpFile = {
    step1 : function(){
        $(".helpFileForSteps").live("click", function(){
            action = $(this).attr("data-action");
            steps = $(this).attr("data-steps");
            $("#modalBox").html(null)
            if(steps=="help"){
                $.get("/ajaxHelp/"+steps,function(e){
                    $("#modalBox").html(e).css({"margin-left":"-330px",
                                               "top": "50px",
                                               "width":"800px",
                                               "height": "550px",
                                               "left": "42%"});
                });
            }
        });
    },
    helpStep : function(){
        $(".showNeedHelp").live("click", function(){
            action = $(this).attr("data-action");
            $(".checklistStep").hide();
        });
    }
}
$(document).ready(function(){
//---------------------------------------------------------------------------------------------//
    // Sending Message to the selected user
    message.loadMessage();
    message.sendMessage();
    message.replyMessage();
    message.deleteMessage();
    message.selectToDeleteMessage();
    message.deleteMessageFromDB();
    message.cancelDeleteMessage();
    message.inboxMessage();
    message.refresher();
    // Checking Checkbox
    checkbox.singleSelect(".singleSelectAll");
    checkbox.selectAll();
    // Login Functions
    loginAuth.login(); // redirect user to the formalistic
    loginAuth.getImage(); // Get user image to identify 
    
    // Tbl Plugin (Search, table plug, sorting)
    // Advance Searching
    table.searchByDateRequestToApprove(".searchByDate"); // Enabling Searching for date
    table.searchAllRequestToApprove(".searchAll"); // Enabling Searching for all
    table.defaultDaRequestToApprove(".defaultDa"); // Enabling Searching for Default 
    
    // Searching
    //table.search_requestApprove(".searchRA"); // Search Request To Approve
    table.search_requestApprove_alls(".searchRAall"); // Search All
    table.searchDate("#searchDateRequestToApprove"); // Search Date
    
    // For New Searching
    table.recordSearch(".recordSearch"); // Search Active Tab
    
    
    // Sorting
    table.sortRequestApprove("#sortRequestApprove"); // Sorting Request To Approve Table
    table.sortRequestApprove("#sortPendingAction"); // Sorting Request To Approve Table
    table.sortRequestApprove("#sortMyRequest"); // Sorting Request To Approve Table
    // Pagination
    table.tablePagination('.pagination li.active'); // For pagination
    
    $(".dateFormatSearch").datepicker({ dateFormat: 'yy-mm-dd' });
//---------------------------------------------------------------------------------------------//
    // Create Form Page Module
    craeteForm.setviewCreatedForm(".setviewCreatedForm"); // View Form when Workflow is activated in the tab
        /* Tab Functions */
        $(".tab_content").hide();
        $(".tab_content:first").show();
        craeteForm.tab();
        
//---------------------------------------------------------------------------------------------//
    // For Modal Box 
    modal.showModal(".modal"); //Per action of modal
//---------------------------------------------------------------------------------------------//
    // Users (Add)
    users.registration(); // Add new user
    users.registrationCompany(); // Add new Company Group
});




    myFunctions.menuHoveringIn();
    myFunctions.menuHoveringOut();
    myFunctions.advanceSearching();
    myFunctions.collapseTab();
    
//---------------------------------------------------------------------------------------------//
    // For Edit information
    user_info.editBasicInfo();
    user_info.showEditInfo(); // Show Field to edit
    user_info.showCancelEdit(); // Cancel Editing
    user_info.updateUsername(); // Update Username
    user_info.updatePassword(); // Update Password


// Call Function - Plugin for this Administer Module
administerModule.viewMore("#loadMore"); // View More Announcement.
administerModule.lessMore("#lessMore"); // Limit view of the characters in Announcement.
//administerModule.saveNewAnnouncement(".btnAnnouncement"); // Save new annoucement.
administerModule.appendNumCols("#appendNumCols"); // Show created columns according to their inputed value.
administerModule.saveSetofCols("#saveSetofCols"); // Save created/set of columns to the database.
administerModule.selectLabel(".selectLabel");
administerModule.enabledCol(".enabledCol");
administerModule.removeSelectedField("#removeSelectedField");
administerModule.saveModSettings("#saveModSettings");

// For Steps Procedures
helpFile.step1(); // For Step1
helpFile.helpStep(); // For HelpFIle
/***************************************************************************************************************************************/
/******************************************************OWN FUNCTIONS********************************************************************/
/* Create Functions */
function tblRequestToApprove(action,page,elementsShow,dataSortValue,counterSort,data_location){
    $.post("/ajaxTable/"+data_location, {action:action,page:page,dataSortValue:dataSortValue,counterSort:counterSort}, function(table){
        $(elementsShow).html(table);
    });
}
/* Load MEssage */
function loadMessage(){
    $(".leftMessagePanel").fadeIn();
    $.post("/ajax/getMessage",{action:"loadMessage"},function(e){
        $(".leftMessagePanel").html(e);
    });
}
